import React, {useEffect, useState} from "react";
import {Button, Card, message, Modal, Row} from "antd";
import {DeleteOutlined, EditOutlined, PlusOutlined} from "@ant-design/icons";
import departmentService from "@/services/department";
import {arrayToTree} from "@/utils/utils";
import {DepartmentVO} from "@/types/department";
import {DepartmentCreateForm, DepartmentModifyForm} from "../Form";
import CustomTree from "@/components/CustomTree";
import {OptionType} from "@/types/common";
import styles from "./index.less";



interface DepartmentListProps {
  selectedKeys?: (string | number)[];
  onSelect?: (value:(string | number)[])=>void;
}

const DepartmentList: React.FC<DepartmentListProps> = (props:DepartmentListProps) => {

  const queryList=async ()=>{
    departmentService.queryListByCurrentOrganization({})
      .then(({data})=>{
        setOptions(arrayToTree(data));
        setLoading(false);
      })
  }

  const _delete=async (params:any)=>{
    const response=await departmentService.deleteByCurrentOrganization(params)
    const {exception}=response;
    if(!exception){
      message.success('删除成功');
      queryList();
    }
  }

  useEffect(() => {
    queryList();
  },[]);

  const [createModalVisible, handleCreateModalVisible] = useState<boolean>(false);
  /**
   * @en-US The pop-up window of the distribution update window
   * @zh-CN 分布更新窗口的弹窗
   * */
  const [modifyModalVisible, handleModifyModalVisible] = useState<boolean>(false);

  const [currentRow, setCurrentRow] = useState<DepartmentVO |undefined>(undefined);

  const [options, setOptions] = useState<OptionType[]>([]);

  const [loading, setLoading] = useState<boolean>(true);

  const showCreateModal=(record?:DepartmentVO) => {
    handleCreateModalVisible(true);
    setCurrentRow(record);
  }

  const hideCreateModal=() => {
    setCurrentRow(undefined);
    handleCreateModalVisible(false);
  }

  const showModifyModal=(record:DepartmentVO) => {
    handleModifyModalVisible(true);
    setCurrentRow(record);
  }

  const hideModifyModal=()=>{
    setCurrentRow(undefined);
    handleModifyModalVisible(false);
  }

  const showDeleteModal=(record:DepartmentVO) => {
    Modal.confirm({
      title: '是否删除该部门',
      content: record.name,
      onOk:()=>{
        // @ts-ignore
        _delete({id: record.id});
      }
    })
  }

  const resetCreateModal=()=>{
    hideCreateModal();
    queryList();
  }

  const resetModifyModal=()=>{
    hideModifyModal();
    queryList();
  }

  return (
    <Card
      bordered={false}
      title={'部门列表'}
      className={styles.left}
      extra={
        <Button type={"primary"} onClick={()=>showCreateModal()}>
          <PlusOutlined />
          新建部门
        </Button>
      }
    >
      <CustomTree
        value={props.selectedKeys}
        onChange={props.onSelect}
        list={options}
        loading={loading}
        renderTitle={(record)=>{
          return (
            <Row
              onMouseEnter={() => {
                setCurrentRow(record);
              }}
              onMouseLeave={() => {
                setCurrentRow(undefined);
              }}
            >
              {record.name}
              {currentRow&&currentRow.id === record.id && (
                <>
                  <Button
                    type={'link'}
                    size={'small'}
                    onClick={e => {
                      e.stopPropagation();
                      showCreateModal(record);
                    }}
                  >
                    <PlusOutlined />
                  </Button>
                  <Button
                    type={'link'}
                    size={'small'}
                    onClick={e => {
                      e.stopPropagation();
                      showModifyModal(record);
                    }}
                  >
                    <EditOutlined />
                  </Button>
                  <Button
                    type={'link'}
                    size={'small'}
                    onClick={e => {
                      e.stopPropagation();
                      showDeleteModal(record)
                    }}
                  >
                    <DeleteOutlined />
                  </Button>
                </>
              )}
            </Row>
          )
        }}
      />
      {createModalVisible && (
        <DepartmentCreateForm
          entity={{
            parentId:currentRow?.id,
            organizationId:currentRow?.organizationId,
          }}
          options={options}
          visible={createModalVisible}
          onReset={resetCreateModal}
          onHide={hideCreateModal}
        />
      )}
      {modifyModalVisible && (
        <DepartmentModifyForm
          entity={currentRow}
          options={options}
          onReset={resetModifyModal}
          visible={modifyModalVisible}
          onHide={hideModifyModal}
        />
      )}
    </Card>
);
};

export default DepartmentList
